﻿Imports System.Text
Imports System.Net
Imports System.IO
Namespace Darkorbit
    Public Class Account

#Region "Getter"
        Private _Username As String = String.Empty
        Public ReadOnly Property Username As String
            Get
                Return _Username
            End Get
        End Property

        Private _Password As String = String.Empty
        Public ReadOnly Property Password As String
            Get
                Return _Password
            End Get
        End Property

        Private _Server As String = String.Empty
        Public ReadOnly Property Server As String
            Get
                Return _Server
            End Get
        End Property

        Private _Cookies As CookieContainer = New CookieContainer
        Public ReadOnly Property Cookies As CookieContainer
            Get
                Return _Cookies
            End Get
        End Property

        Private _UserId As UInteger = 0
        Public ReadOnly Property UserId As UInteger
            Get
                Return _UserId
            End Get
        End Property

        Private _SessionId As String = String.Empty
        Public ReadOnly Property SessionId As String
            Get
                Return _SessionId
            End Get
        End Property
#End Region

        Sub New(ByVal Username As String, ByVal Password As String, ByVal Server As String)
            _Username = Username
            _Password = Password
            _Server = Server
        End Sub

        Sub initialize()
            _UserId = getUserId()
            _SessionId = getSessionId()
        End Sub

        Public Function login() As Boolean
            Try
                Dim sb As StringBuilder = New StringBuilder()
                sb.Append("loginForm_default_username=")
                sb.Append(_Username)
                sb.Append("&loginForm_default_password=")
                sb.Append(_Password)
                sb.Append("&loginForm_default_login_submit=Login")


                Dim sLogged As String = httpPost("http://www.darkorbit.com/?locale=us&aid=0", sb.ToString)

                Dim str As String() = sLogged.Split("<"c)

                For i As Integer = 0 To str.Count - 1
                    If str(i).Contains("http://" & _Server & ".darkorbit.bigpoint.com/GameAPI.php?") Then
                        Dim url As String = getBetween(str(i), "target=""", Chr(34))
                        _Cookies = New CookieContainer
                        Dim second As String = httpGet(url)
                        If second.Trim() = "" Then
                            Return False
                        End If
                        Return second.Contains(_Username)
                    End If
                Next
                Return False
            Catch ex As Exception
                Return False
            End Try
        End Function

        Public Function getUridium() As Integer
            Dim str As String = httpGet("http://" & _Server & ".darkorbit.bigpoint.com/indexInternal.es?action=internalStart")

            For i As Integer = 0 To str.Split("<"c).Count - 1
                If str.Split("<"c)(i).Contains("a id=""header_uri"" class=""header_money""") Then
                    Return CType(str.Split("<"c)(i).Split(">"c)(1).Trim(), Integer)
                End If
            Next
            Return 0
        End Function

        Public Function getCredits() As Integer
            Dim str As String = httpGet("http://" & _Server & ".darkorbit.bigpoint.com/indexInternal.es?action=internalStart")

            For i As Integer = 0 To str.Split("<"c).Count - 1
                If str.Split("<"c)(i).Contains("div id=""header_credits"" class=""header_money") Then
                    Return CType(str.Split("<"c)(i).Split(">"c)(1).Trim().Replace(",", ""), Integer)
                End If
            Next
            Return 0
        End Function

        Public Function getUserId() As UInteger
            Dim str As String = httpGet("http://" & _Server & ".darkorbit.bigpoint.com/indexInternal.es?action=internalStart")

            Return CType(getBetween(str, "userKeyId     : '", "',"), UInteger)
        End Function

        Public Function getSessionId() As String
            Dim str As String = httpGet("http://" & _Server & ".darkorbit.bigpoint.com/indexInternal.es?action=internalStart")

            Return getBetween(str, "'dosid=", "');")
        End Function

        Public Sub spinGalaxyGate(ByVal gateId As Integer, ByVal gateToString As String, ByVal amount As Integer)
            Dim str As String = httpGet("http://" & _Server & ".darkorbit.bigpoint.com/flashinput/galaxyGates.php?userID=" & _UserId & "&action=multiEnergy&sid=" & _SessionId & "&gateID=" & gateId.ToString & "&" & gateToString & "=" & gateId.ToString & "&sample=" & amount.ToString)
        End Sub

        Public Function getGateImage(ByVal gateId As Integer, Optional ByVal type As String = "full") As Image
            Dim tmpImage As Image = Nothing

            Dim request As HttpWebRequest = CType(HttpWebRequest.Create("http://us3.darkorbit.bigpoint.com/jumpgate.php?userID=" & _UserId & "&gateID=" & gateId & "&type=" & type), HttpWebRequest)
            request.CookieContainer = _Cookies
            request.AllowWriteStreamBuffering = True
            Dim webResponse As WebResponse = request.GetResponse()
            Dim webStream As System.IO.Stream = webResponse.GetResponseStream()
            tmpImage = Image.FromStream(webStream)
            webResponse.Close()

            webResponse.Close()
            Return tmpImage
        End Function

        Private Function generateReloadToken() As String
            Dim useablechars As String() = {"a", "e", "i", "o", "u", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}

            Dim str As String = String.Empty

            For i As Integer = 0 To 31
                str &= useablechars(New Random().Next(useablechars.Count - 1))
            Next
            Return str
        End Function

        Public Sub upgradeSkylab(ByVal construction As String, Optional ByVal instant As Boolean = False)
            If instant Then
                httpGet("http://" & _Server & ".darkorbit.bigpoint.com/indexInternal.es?action=internalSkylab&subaction=instantUpgrade&construction=" & construction & "&reloadToken=" & generateReloadToken())
                Exit Sub
            End If
            httpGet("http://" & _Server & ".darkorbit.bigpoint.com/indexInternal.es?action=internalSkylab&subaction=upgrade&construction=" & construction & "&reloadToken=" & generateReloadToken())
        End Sub

        Public Sub buildTechCenter(ByVal type As String, ByVal level As Integer, Optional ByVal instant As Boolean = False, Optional ByVal buy As Boolean = False)
            If instant Then
                httpGet("http://us3.darkorbit.bigpoint.com/indexInternal.es?action=internalNanoTechFactory&subaction=buildBuff&instant=1&buff=" & type & "&level=" & level & "&reloadToken=" & generateReloadToken())
                Exit Sub
            End If
            If buy Then
                httpGet("http://us3.darkorbit.bigpoint.com/indexInternal.es?action=internalNanoTechFactory&subaction=buyBuff&buff=" & type & "&level=" & level & "&reloadToken=" & generateReloadToken())
                Exit Sub
            End If
            httpGet("http://us3.darkorbit.bigpoint.com/indexInternal.es?action=internalNanoTechFactory&subaction=buildBuff&buff=" & type & "&level=" & level & "&reloadToken=" & generateReloadToken())
        End Sub

        Public Sub bid(ByVal itemid As String, ByVal amount As Integer)
            httpGet("http://" & _Server & ".darkorbit.bigpoint.com/indexInternal.es?action=internalAuction&subAction=bid&itemId=" & itemid & "&bid=" & amount.ToString & "&reloadToken=" & generateReloadToken())
        End Sub

        Public Sub buyItem(ByVal itemid As String)
            httpGet("http://" & _Server & ".darkorbit.bigpoint.com/indexInternal.es?action=internalAuction&subAction=buy&lootId=" & itemid & "&reloadToken=" & generateReloadToken() & "&amount=1")
        End Sub

        Public Function counterTimer(ByVal _m As Integer, ByVal _s As Integer)
            _s -= 1
            If _s < 0 Then
                _s = 59
                _m -= 1
            End If
            If _m < 0 Then
                _m = 59
            End If

            Dim __s As String = "" & _s
            If _s.ToString.Length = 1 Then
                __s = String.Format("{0}" & _s, 0)
            End If
            Dim __m As String = "" & _m
            If _m.ToString.Length = 1 Then
                __m = String.Format("{0}" & _m, 0)
            End If

            Return __m & ":" & __s
        End Function
#Region "Http"
        Private Function httpPost(ByVal sUrl As String, ByVal sPost As String) As String
            Try
                Dim nRequest As HttpWebRequest = CType(WebRequest.Create(sUrl), HttpWebRequest)
                nRequest.Method = "POST"
                nRequest.CookieContainer = _Cookies
                nRequest.ContentType = "application/x-www-form-urlencoded"
                Dim nbyteArray() As Byte = Encoding.Default.GetBytes(sPost)
                nRequest.ContentLength = nbyteArray.Length
                Dim nDataStream As Stream = nRequest.GetRequestStream()
                nDataStream.Write(nbyteArray, 0, nbyteArray.Length)
                nDataStream.Close()

                Dim nResponse As HttpWebResponse = CType(nRequest.GetResponse(), HttpWebResponse)
                nDataStream = nResponse.GetResponseStream()
                Dim nreader As New StreamReader(nDataStream)
                Dim nServerResponse As String = nreader.ReadToEnd()
                nreader.Close()
                nDataStream.Close()
                nResponse.Close()

                Return nServerResponse
            Catch ex As Exception
                Return String.Empty
            End Try

        End Function

        Private Function httpGet(ByVal sUrl As String) As String
            Try
                Dim Request As HttpWebRequest = CType(WebRequest.Create(sUrl), HttpWebRequest)
                Request.Method = "GET"
                Request.CookieContainer = _Cookies
                Request.ContentType = "application/x-www-form-urlencoded"

                Dim Response As HttpWebResponse = CType(Request.GetResponse(), HttpWebResponse)
                Dim DataStream = Response.GetResponseStream()
                Dim reader As New StreamReader(DataStream)
                Dim ServerResponse As String = reader.ReadToEnd()
                reader.Close()
                DataStream.Close()
                Response.Close()

                Return ServerResponse
            Catch ex As Exception
                Return String.Empty
            End Try


        End Function

        Private Function getBetween(ByRef strSource As String, ByRef strStart As String, ByRef strEnd As String, Optional ByRef startPos As Integer = 0) As String
            Try
                Dim iPos As Integer, iEnd As Integer, lenStart As Integer = strStart.Length
                Dim strResult As String
                strResult = String.Empty
                iPos = strSource.IndexOf(strStart, startPos)
                iEnd = strSource.IndexOf(strEnd, iPos + lenStart)
                If iPos <> -1 AndAlso iEnd <> -1 Then
                    strResult = strSource.Substring(iPos + lenStart, iEnd - (iPos + lenStart))
                End If
                Return strResult
            Catch
                Return String.Empty
            End Try
        End Function
#End Region

    End Class
End Namespace
